package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.tensquare.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Component
public class ManagerFilter extends ZuulFilter {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public String filterType() {
        //过滤器的类型，也就是执行的时机
        /*
         * pre：可以在请求被路由之前调用
         * route：在路由请求时候被调用
         * post：在route和error过滤器之后被调用
         * error：处理请求时发生错误时被调用
         */
        return "pre";
    }

    @Override
    public int filterOrder() {
        //如果有多个过滤器时，过滤器执行的顺序
        //返回的数字越小，越优先执行
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //是否开启过滤器
        //true：开启。false：关闭
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //过滤器具体执行的逻辑
        //currentContext.setSendZuulResponse(false)，终止执行，返回客户端
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //OPTIONS方法时内部转发的方法。根据配置文件转发到相应的微服务
        if (request.getMethod().equals("OPTIONS")) {
            return null;
        }
        String requestURI = request.getRequestURI();
        if (requestURI.indexOf("login") > 0) {
            return null;
        }
        String header = request.getHeader("Authorization");
        if (!StringUtils.isEmpty(header)) {
            if (header.startsWith("Bearer ")) {
                String token = header.substring(7);
                try {
                    Claims claims = jwtUtil.parseJWT(token);
                    if ("admin".equals(claims.get("roles"))) {
                        return null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        currentContext.setSendZuulResponse(false);//终止运行
        currentContext.setResponseStatusCode(403);
        currentContext.setResponseBody("无权访问");
        currentContext.getResponse().setContentType("text/html;charset=UTF-8");
        return null;
    }
}
